package payment.mobilepos.unionpay.com.demo;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.session.MediaSession;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.com.unionpay.constant.Constant;
import com.com.unionpay.speech.receiver.BluetoothReceiver;
import com.com.unionpay.speech.util.Money2Digit;
import com.sdk.ActiveMode;
import com.sdk.IActivity;
import com.sdk.LogUtils;
import com.sdk.MessageEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import payment.mobilepos.unionpay.com.R;
import payment.mobilepos.unionpay.com.demo.base.UPMPosBaseActivity;
import payment.mobilepos.unionpay.com.demo.widget.CashierKeyboard;

public class MainActivity extends UPMPosBaseActivity implements IActivity {

    private EditText mAmountEdit;
    private CashierKeyboard mCashierKeyboard;

    private String mAmount = "0";


    /**
     * 语音识别
     */
    private static String TAG = "MainActivity";
    protected boolean running = false;
    protected Handler handler;
    protected boolean enableOffline = false;

    private BluetoothReceiver mBluetoothReceiver;

    AudioManager mAudioManager;
    private MediaPlayer mediaPlayer;
    private MediaSession mSession;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initPermission();

        setContentView(R.layout.activity_main);

        findViewById(R.id.nav_btn_right).setOnClickListener(this);
        findViewById(R.id.nav_btn_left).setOnClickListener(this);

        mAmountEdit = findViewById(R.id.edit_amount);
        mCashierKeyboard = findViewById(R.id.cashier_keyboard);
        mCashierKeyboard.setOnInputTextChangedListener(new CashierKeyboard
                .OnInputTextChangedListener() {
            @Override
            public void onInputTextChanged(String text) {
                mAmount = text;
//                mAmountEdit.setText(text);
                updateAmountEdit();
            }
        });
        mCashierKeyboard.setOnPayeeViewClickedListener(new CashierKeyboard
                .OnPayeeViewClickedListener() {
            @Override
            public void onPayeeViewClicked() {
                ActivityUtils.showPayeeSwipeActivity(MainActivity.this, mAmount);
            }
        });

        ContextUtil.hideSoftInputKeyboard(this, mAmountEdit);

        updateAmountEdit();

    }


    @Override
    protected void onResume() {
        super.onResume();
        PermissionUtil.verifyCameraPermissions(this);
        PermissionUtil.verifyRecodeAudioPermissions(this);


    }


    private void updateAmountEdit() {
        SpannableString span = new SpannableString("￥" + mAmount);
        span.setSpan(new AbsoluteSizeSpan(24, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (mAmount.contains(".")) {
            int pointIndex = mAmount.indexOf(".");
            span.setSpan(new AbsoluteSizeSpan(24, true), pointIndex + 1, mAmount.length() + 1,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        mAmountEdit.setText(span);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.nav_btn_left:
                EventBus.getDefault().post(new MessageEvent(Constant.EVENT_CLICK_ACTIVE, ActiveMode.CLICK));

                break;
            case R.id.nav_btn_right:
                ActivityUtils.showCaptureActivity(this);
                break;
        }
    }


    /**
     * android 6.0 以上需要动态申请权限
     */
    private void initPermission() {
        String permissions[] = {
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.MODIFY_AUDIO_SETTINGS,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_SETTINGS,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.BLUETOOTH,
                Manifest.permission.CAMERA,

        };

        ArrayList<String> toApplyList = new ArrayList<String>();

        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
                toApplyList.add(perm);
                //进入到这里代表没有权限.
            }
        }
        String tmpList[] = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 123);
        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // 此处为android 6.0以上动态授权的回调，用户自行实现。
    }


    @Override
    protected void onPause() {
        Log.i(TAG, "onPause");
        super.onPause();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mBatInfoReceiver != null) {
            try {
                unregisterReceiver(mBatInfoReceiver);
            } catch (Exception e) {
                LogUtils.e("unregisterReceiver mBatInfoReceiver failure :"
                        + e.getCause());
            }
        }
        // 解除注册 Home
        if (homePressReceiver != null) {
            try {
                unregisterReceiver(homePressReceiver);
            } catch (Exception e) {
                LogUtils.e("unregisterReceiver homePressReceiver failure :"
                        + e.getCause());
            }
        }
    }


    private final BroadcastReceiver homePressReceiver = new BroadcastReceiver() {
        final String SYSTEM_DIALOG_REASON_KEY = "reason";
        final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                if (reason != null
                        && reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
                    // 自己随意控制程序，关闭...
                }
            }
        }

    };
    private final BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, final Intent intent) {

            final String action = intent.getAction();
            if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                LogUtils.e("get Key KEYCODE_POWER(KeyCode:26)-OFF");
            } else if (Intent.ACTION_SCREEN_ON.equals(action)) {
                LogUtils.e("get Key KEYCODE_POWER(KeyCode:26)-NO");
            }
        }
    };


    @Override
    public List<Enum<ActiveMode>> getSpeechActiveMode() {
        List<Enum<ActiveMode>> modes = new ArrayList<>();
        modes.add(ActiveMode.BLUETOOTH);
        modes.add(ActiveMode.CLICK);
        modes.add(ActiveMode.SPEECH_WAKEUP);
        modes.add(ActiveMode.MQTT);

        return modes;
    }

    @Override
    public void doSpeechEnd(String result) {

        // 转换成数字
        LogUtils.e("result=" + result);
        String money = Money2Digit.convertToPinyin2Num(result);
        Log.i(TAG, "money: " + money);

        if ("".equals(money) || null == money
                || "0".equals(money)) {
            // Log.i(TAG, "handleMessage: " + msg);


        } else {
            ActivityUtils.showPayeeSwipeActivity(MainActivity.this, money);
        }

    }

    @Override
    public boolean showEasyTouch() {
        return true;
    }


}
